package momo.app.structure;

import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.StringTokenizer;

public class StabMap
{
	private Map<String, StabRecord> map;
	
	public StabMap()
	{
		map = Collections.synchronizedMap(new HashMap<String, StabRecord>());
	}
	
	public void noteTimeJoined(String id)
	{
		StabRecord rc = map.get(id);
		if ( rc == null )
		{
			rc = new StabRecord(0);
			map.put(id, rc);
		}
		rc.noteTimeJoined();
	}
	
	public void leave(String id)
	{
		StabRecord rc = map.get(id);
		if ( rc == null )
			throw new RuntimeException("Should not have null objects leaving");
		
		rc.leave();
	}
	
	public void resetDurationCal(String id)
	{
		StabRecord rc = map.get(id);
		if ( rc == null )
			throw new RuntimeException("Should not have null objects resetting");
		
		rc.resetDurationCal();
	}
	
	public void reconstuct(String id)
	{
		StabRecord rc = map.get(id);
		if ( rc == null )
			throw new RuntimeException("Should not have null objects resetting");
		
		rc.reconstruct();
	}
	
	public double getStability(String id)
	{
		StabRecord rc = map.get(id);
		if ( rc == null )
			throw new RuntimeException("Should not have null objects resetting");
		
		return rc.getStability();
	}
	
	public double getActiveStability(String id)
	{
		StabRecord rc = map.get(id);
		if ( rc == null )
			throw new RuntimeException("Should not have null objects resetting");
		
		return rc.getActiveStability();
	}
	
	public void update(String contents)
	{
		StringTokenizer pipeTokens = new StringTokenizer(contents, "|");
		while ( pipeTokens.hasMoreTokens() )
		{
			String mainContents = pipeTokens.nextToken();
			StringTokenizer mainTokens = new StringTokenizer(mainContents, ",");
			
			String id = mainTokens.nextToken();
			double duration = Double.parseDouble(mainTokens.nextToken());
			double stability = Double.parseDouble(mainTokens.nextToken());
			double avgSession = Double.parseDouble(mainTokens.nextToken());
			
			StabRecord rc = new StabRecord(duration, stability, avgSession);
			rc.noteTimeJoined();
			map.put(id, rc);
		}
	}
	
	public String toString()
	{
		StringBuffer buffer = new StringBuffer();
		Iterator<String> iterKey = map.keySet().iterator();
		while ( iterKey.hasNext() )
		{
			String id = iterKey.next();
			StabRecord rc = map.get(id);
			buffer.append(id);
			buffer.append(",");
			buffer.append(rc.toString());
			buffer.append("|");
		}
		return buffer.toString();
	}
	
	public String testDisplayString()
	{
		StringBuffer buffer = new StringBuffer();
		Iterator<String> iterKey = map.keySet().iterator();
		while ( iterKey.hasNext() )
		{
			String id = iterKey.next();
			StabRecord rc = map.get(id);
			buffer.append(id);
			buffer.append(": ");
			buffer.append(rc.toString());
			buffer.append("\n");
		}
		return buffer.toString();
	}
}//end of class StabMap
